package com.lehecai.core.lottery.content.impl;

import com.lehecai.core.exception.lottery.content.UnsupportedElementAttributeException;
import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.content.IElementAttribute;
import org.apache.commons.lang.StringUtils;

/**
 * User: sunshow
 */
public class LotteryTypeSpecifiedElementAttributeParser extends CommonElementAttributeParser {

    @Override
    public IElementAttribute parse(String attribute) throws UnsupportedElementAttributeException {
        // 必须是以$分开的两组数据
        String[] groups = StringUtils.split(attribute, IElementAttribute.ATTRIBUTE_SEPARATOR);

        if (groups.length != 2) {
            logger.error("分组属性个数不正确, attribute={}", attribute);
            throw new UnsupportedElementAttributeException("分组属性个数不正确");
        }

        // 不能为空
        if (StringUtils.isBlank(groups[0]) || StringUtils.isBlank(groups[1])) {
            logger.error("分组属性不能为空, attribute={}", attribute);
            throw new UnsupportedElementAttributeException("分组属性不能为空");
        }

        // 第二组元素必须能转换成LotteryType
        LotteryType lotteryType = null;
        try {
            lotteryType = LotteryType.getItem(Integer.parseInt(groups[1]));
        } catch (NumberFormatException e) {
            logger.error(e.getMessage(), e);
        }
        if (lotteryType == null) {
            logger.error("彩种属性不正确, attribute={}", attribute);
            throw new UnsupportedElementAttributeException("彩种属性不正确");
        }

        return new LotteryTypeSpecifiedElementAttribute(groups[0], lotteryType);
    }

}
